package cn.tianjindong.blog_manager.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tianjindong.blog.mapper.BlogArticleCategoryMapper;
import cn.tianjindong.blog.mapper.BlogArticleMapper;
import cn.tianjindong.blog.pojo.BlogArticle;
import cn.tianjindong.blog.pojo.BlogArticleCategory;
import cn.tianjindong.blog.pojo.BlogArticleCategoryExample;
import cn.tianjindong.blog.pojo.BlogArticleCategoryExample.Criteria;
import cn.tianjindong.blog.pojo.BlogArticleExample;
import cn.tianjindong.blog_manager.service.CategoryService;

@Service
public class CategoryServiceIml implements CategoryService {

	@Autowired
	private BlogArticleCategoryMapper categoryMapper;

	@Autowired
	private BlogArticleMapper articleMapper;

	@Override
	public void addArticleCategory(BlogArticleCategory category) {
		Date date = new Date();
		category.setUpdatetime(date);
		category.setCreatetime(date);
		categoryMapper.insert(category);
	}

	@Override
	public List<BlogArticleCategory> getAllCategory() {
		BlogArticleCategoryExample example = new BlogArticleCategoryExample();
		// 通过level排序(level代表 BlogArticleCategory的优先级)
		example.setOrderByClause("level");
		List<BlogArticleCategory> list = categoryMapper.selectByExample(example);

		// 获取每个分类的文章数
		for (BlogArticleCategory category : list) {
			BlogArticleExample example2 = new BlogArticleExample();
			cn.tianjindong.blog.pojo.BlogArticleExample.Criteria criteria = example2.createCriteria();
			criteria.andCategoryIdEqualTo(category.getId());
			int num = articleMapper.countByExample(example2);
			category.setArticleNum(num);
		}
		return list;
	}

	@Override
	public BlogArticleCategory getCategoryById(Long id) {
		BlogArticleCategory category = categoryMapper.selectByPrimaryKey(id);
		return category;
	}

	@Override
	public void updateCategory(BlogArticleCategory category) {
		Date date=new Date();
		category.setUpdatetime(date);
		categoryMapper.updateByPrimaryKeySelective(category);
	}

	@Override
	public void deleteCategory(Long id) {
		categoryMapper.deleteByPrimaryKey(id);
	}

}
